import _ from 'lodash';
import { getDeepObjectProperty } from '@/utils/obj';

export default {
  data() {
    return {
      fill_value: ''
    };
  },

  watch: {
    value: {
      immediate: true,
      handler(val = {}) {
        const { choice = '', fill = '' } = val;
        this.inputValue = choice || '';

        const index = _.findIndex(
          this.choice,
          ({ id }) => id === choice
        );

        if (index > -1) {
          this.fill_value = fill;
        }
      }
    },

    choice: {
      immediate: true,
      handler(val) {
        // 远程
        if (this.remote) {
          this.fetchRemoteChoice && this.fetchRemoteChoice();
        } else {
          const { data } = this.defaultProps;
          const { label, value, has_fill } = data;

          const isProperty = (o) => !!getDeepObjectProperty(has_fill, o);

          this.option = _.map(
            val, (o) => {
              const v = o[value];
              const isV = (this.inputValue === v);

              return {
                field_value: o[value],
                field_label: o[label],
                has_fill: isProperty(o),
                fill_value: isV ? this.fill_value : '',
                prop: this.createInput({ fields: o })
              };
            }
          );
        }
      }
    }
  },

  methods: {
    // 重置内容
    resetValue() {
      if (this.canDo) return this.inputValue;
      const { type, fill } = this.collectProps;
      this.inputValue = '';
      this.toggleEvent('change', {
        [type]: this.inputValue,
        [fill]: ''
      });
    },

    // 表单验证
    validate(option = { first: true }) {
      return new Promise((resolve, reject) => {
        this.errorMessage = '';
        this.$nextTick(async () => {
          if (this.canDo) {
            resolve(true);
            return false;
          }

          const ref = 'vanSelectInput';
          const _validateList = [this.createSchema(option)];

          // select input
          _.forEach(this.option, ({ field_value, has_fill }, i) => {
            const val = this.inputValue;
            if (val === field_value && has_fill) {
              const { createSchema } = this.$refs[ref + i][0];
              createSchema && _validateList.push(createSchema(option));
            }
          });
          try {
            await Promise.all(_validateList);
            resolve(true);
          } catch ({ errors: [{ message }] }) {
            this.errorMessage = message;
            reject({ message, dom: this.refCustomForm });
          }
        });
      });
    }
  }
};
